import { createVNode, render } from 'vue'
import AddDish from '@/views/home/components/dish/components/Add.vue'
import { ElDrawer } from 'element-plus'

type AddDishCallback = (dish: any) => void
type CloseCallback = () => void

/**
 * 以函数形式调用 Add.vue 组件并显示抽屉
 * @param onAddDish - 添加菜品成功时的回调函数
 * @param onClose - 抽屉关闭时的回调函数
 */
export const showAddDishDrawer = (
  onAddDish: AddDishCallback,
  onClose?: CloseCallback
) => {
  // 创建容器元素
  const container = document.createElement('div')
  document.body.appendChild(container)

  // 关闭并清理抽屉
  const closeDrawer = () => {
    render(null, container)
    document.body.removeChild(container)
    if (onClose) onClose()
  }
1
  // 处理添加菜品事件
  const handleAddDish = (dish: any) => {
    onAddDish(dish)
    closeDrawer()
  }

  // 创建抽屉VNode
  const drawerVNode = createVNode(
    ElDrawer,
    {
      modelValue: true,
      title: '添加菜品',
      direction: 'rtl',
      beforeClose: closeDrawer,
      onClose: closeDrawer,
      destroyOnClose: true
    },
    {
      default: () => createVNode(AddDish, {
        onAddDish: handleAddDish,
        onClose: closeDrawer
      })
    }
  )

  // 渲染抽屉
  render(drawerVNode, container)

  // 返回关闭函数，允许外部主动关闭抽屉
  return closeDrawer
}